// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/base/fs.h>

#include <fmt/format.h>
#include <turbo/log/logging.h>

namespace kumo::pollux::common {
    bool generateFileDirectory(const char *dirPath) {
        std::error_code errorCode;
        const auto success = fs::create_directories(dirPath, errorCode);
        fs::permissions(dirPath, fs::perms::all, fs::perm_options::replace);
        if (!success && errorCode.value() != 0) {
            KLOG(ERROR) << "Failed to create file directory '" << dirPath
                    << "'. Error: " << errorCode.message() << " errno "
                    << errorCode.value();
            return false;
        }
        return true;
    }

    std::optional<std::string> generateTempFilePath(
        const char *basePath,
        const char *prefix) {
        auto path = fmt::format("{}/pollux_{}_XXXXXX", basePath, prefix);
        auto fd = mkstemp(path.data());
        if (fd == -1) {
            PKLOG(ERROR) << "Failed to create temporary file '" << path;
            return std::nullopt;
        }
        return path;
    }

    std::optional<std::string> generateTempFolderPath(
        const char *basePath,
        const char *prefix) {
        auto path = fmt::format("{}/pollux_{}_XXXXXX", basePath, prefix);
        auto createdPath = mkdtemp(path.data());
        if (createdPath == nullptr) {
            PKLOG(ERROR) << "Failed to create temporary file '" << path;
            return std::nullopt;
        }
        return path;
    }
} // namespace kumo::pollux::common
